package com.helloandroid.services

import androidx.core.content.edit
import com.helloandroid.MyApplication
import com.helloandroid.tools.IntentValue
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils

class LocalSignInfo(
        var bFlagSign: Boolean = true, // true 表示玩家开启了签到提醒, false 表示玩家没有打开签到提醒
        private var lastSignTimeMs : Long = 0L,  // 上次签到时间
        var lastSignTimeMs_Remind : Long = 0L, // 上次提醒的时间
){
    companion object{
        const val PrefSign = "s_pref_sign"

        // 上次签到的时间
        const val KeyLastSignTimeMs = "key_last_sign_time"

        // 上次发送签到通知的时间
        const val KeyLastSignRemindTimeMs = "key_sign_remind_time"

        // 玩家是否开启了签到提醒
        const val KeyFlagSign = "key_flag_sign"
    }
    fun init(){
        val pref = MyApplication.getPerference(PrefSign)
        lastSignTimeMs = pref.getLong(KeyLastSignTimeMs, 0L)

        // 上次提醒的时间
        lastSignTimeMs_Remind = pref.getLong(KeyLastSignRemindTimeMs,0L)
        bFlagSign = pref.getBoolean(KeyFlagSign,true)
    }
    fun check(service: ServerService,serverTimeMs:Long):Boolean{
        // 签到还没固定通知时间
        // 条件: 1.玩家开启了签到提醒
        //       2.玩家当前还没有签到
        //       3.今天没有提醒过
        if (bFlagSign) {

            val curDayTime = MyTimeUtils.dayTimeString(serverTimeMs)

            // 判断是否签到? 如果已经签到,则不需要通知
            if (curDayTime == MyTimeUtils.dayTimeString(lastSignTimeMs)){
                return false
            }

            // 判断是否提醒
            val remindDayTime = MyTimeUtils.dayTimeString(lastSignTimeMs_Remind)
            if (curDayTime == remindDayTime){
                return false
            }

            // 发送通知
            service.sendRemindNotify("签到时间到", "最大价值38元红包等您领取,签到即可获得!", IntentValue.Int_Sign)
            MyApplication.getPerference(PrefSign).edit(commit = true) {
                putLong(KeyLastSignRemindTimeMs, serverTimeMs)
            }
            lastSignTimeMs_Remind = serverTimeMs
            return true
        }
        return false
    }

    fun clearData(){
        MyApplication.getPerference(PrefSign).edit(commit = true){
            clear()
        }
    }

    fun saveSignTime(time:Long){
        MyApplication.getPerference(PrefSign).edit(commit = true){
            putLong(KeyLastSignTimeMs,time)
        }
        lastSignTimeMs = time
        MyLog.info("保存上次签到时间成功!")
    }

    fun  updateFlag(newFlag:Boolean){
        if (bFlagSign != newFlag){
            bFlagSign = newFlag
            MyApplication.getPerference(PrefSign).edit(commit = true){
                putBoolean(KeyFlagSign,bFlagSign)
            }
        }
    }
}